//
//  SCNStringExtension.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/3/10.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import Foundation
import UIKit

extension String {
    /**
     *   MD5
     **/
    func md5() -> String {
        
        let str = self.cString(using: String.Encoding.utf8)
        
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        
        for i in 0 ..< digestLen {
            
            hash.appendFormat("%02x", result[i])
            
        }
        
        result.deinitialize()
        
        return String(format: hash as String)
    }
    /**
     *   字符大小
     **/
    func getTextRectSize(font: UIFont,size: CGSize) -> CGRect {
        
        let attributes = [NSFontAttributeName: font]
        
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        
        let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        
        return rect;
        
    }
    /**
     *   属性字符
     **/
    func changeAttributedString(_ text: String,range: NSRange,font: Float,color: UIColor) -> NSMutableAttributedString {
        
        let attributedString = NSMutableAttributedString(string: text)
        
        attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: CGFloat(font)), range: range)
        
        attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
        
        return attributedString
    }
}
